package com.eascs.admin.o2o.internal.controller;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.item.service.O2oPubDdItemService;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpand;
import com.eascs.admin.o2o.internal.entity.PubDditem;
import com.eascs.admin.o2o.internal.service.LoanapplyExpandService;
import com.eascs.admin.o2o.internal.service.PubDditemService;
import com.eascs.admin.o2o.internal.util.MoneyUtil;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.common.doc.pdf.PdfBuilder;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.nsEditDetail.entity.CustomerAssetInfo;
//import com.eascs.crm.common.entity.CustomerAssetInfoEntity;
//import com.eascs.crm.common.entity.CustomerBasicInfoEntity;
//import com.eascs.crm.common.entity.CustomerExpansionInfoEntity;
//import com.eascs.crm.common.entity.CustomerShopInfoEntity;
import com.eascs.crm.nsEditDetail.entity.CustomerShopInfoEntity;
import com.eascs.crm.nsEditDetail.service.CustomerAssetInfoService;
//import com.eascs.crm.common.entity.PubDditem;
//import com.eascs.crm.common.service.ICustomerInfoService;
//import com.eascs.crm.common.vo.CustomerView;
//import com.eascs.crm.common.vo.QueryCustomerVO;
import com.eascs.crm.nsEditDetail.service.CustomerShopInfoService;
import com.eascs.gaczcontract.entity.CustomerBasicInfo;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sys.SysOrgService;

/**
 * @ClassName: ProtocolRestController
 * @Description: o2oz金融协议打印
 * @author 张庆奇
 * @date 2016年6月12日 下午1:48:48
 * @version V1.0
 */
@RestController
public class ProtocolRestController extends BaseRestController {
//	@Reference
//	private ICustomerInfoService customerInfoService;
	@Autowired
	private O2oLoanapplyService loanService;
	@Autowired
	LoanapplyExpandService loanapplyExpandService;
	@Autowired
	PubDditemService pubDditemService;
	@Reference
	SysOrgService sysOrgService;
	@Autowired
	CustomerShopInfoService shopInfoService;
	@Autowired
	O2oLoanUserService loanUserService;
	@Autowired
	CustomerAssetInfoService assetInfoService;
	@Autowired
	private O2oPubDdItemService o2oPubDdItemService;
	
	
	@RequestMapping(value="/checkShopInfo")
	public BaseRestResult<String> checkShopInfo(String shopId,String loanapplyNo){
//		QueryCustomerVO vo=new QueryCustomerVO();
//		vo.setCustomer_shop_id(shopId);
//		CustomerShopInfoEntity entity=customerInfoService.getCustomerShopInfoEntity(vo);
		
		CustomerShopInfoEntity shop = new CustomerShopInfoEntity();
		List<CustomerShopInfoEntity> infoList = shopInfoService.list(loanapplyNo);//门店信息
		if (!infoList.isEmpty()) {
			if (infoList.size() > 1) {
				for (CustomerShopInfoEntity shopInfo : infoList) {
					if (shopInfo.getShoptype().equals("MAN")) {// 客户主门店里面的营业面积
						shop = shopInfo;
					}
				}
			} else {
				shop = infoList.get(0);
			}
		}
//		if(StringUtils.isEmpty(shop.getControllername()) || StringUtils.isEmpty(shop.getControllerIdnum())|| StringUtils.isEmpty(shop.getControllerMobile())){
		if (StringUtils.isEmpty(shop.getControllername())) {
			return BaseRestResult.warn("请先保存门店信息");
		}
		return BaseRestResult.info("正在下载中...").andRedirect("/makeProtocolPdf?loanapplyNo="+loanapplyNo);
	}
	/**
	 * @Title: downloadProtocolPdf
	 * @Description: 生产pdf，并且下载pdf
	 * @author 张庆奇
	 * @param httpServletResponse
	 * @return void
	 * @throws @date
	 *             2016年6月12日 下午1:59:49
	 */
	@RequestMapping(value = "/makeProtocolPdf", method = RequestMethod.GET)
	public void downloadProtocolPdf(HttpServletResponse httpServletResponse, HttpServletRequest request,
			String loanapplyNo) {
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		if(loanapply==null){
			return;
		}
//		QueryCustomerVO vo = new QueryCustomerVO();
//		vo.setCustomer_id(loanapply.getLoanId());
//		CustomerBasicInfoEntity customer = customerInfoService.getCustomerBasicInfoEntity(vo);
//		if(customer==null){
//			return;
//		}
		
		O2oLoanUserEntity loanUserEntity = loanService.findLoanUserEntity(loanapplyNo, loanapply.getLoanId());
		CustomerBasicInfo customerBasicInfo = loanService.getCustomerEntityById(loanUserEntity.getId());
	
		//最后需要生产的模板文件
		String[] classPathFiles={ "/pdfTemplate/protocol.pdf","/pdfTemplate/protocol.pdf"};
		
			Map<String, Object> data = fillData(loanapplyNo,loanUserEntity,customerBasicInfo);

			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			try {
				PdfBuilder.mergePdfFilesAndBuild(classPathFiles, data, outputStream);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
			OutputStream os = null;
			try {
				String outfile = "";
				outfile = loanUserEntity.getUserFullName() + "-O2O金融合作协议.pdf";// 乙方(借款人)姓名
				if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
					outfile = URLEncoder.encode(outfile, "UTF-8");
				} else {
					outfile = new String(outfile.getBytes("UTF-8"), "ISO8859-1");
				}
				os = httpServletResponse.getOutputStream();
				httpServletResponse.reset();
				httpServletResponse.setContentType("application/pdf");
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
				os.write(outputStream.toByteArray());
				os.flush();
			} catch (IOException e) {
				throw new RuntimeIOException(e);
			} finally {
				IoUtil.close(os);
			}
		
	}

	/**
	 * @Title: fillData
	 * @Description: 填充pdf数据
	 * @author 张庆奇、LMX
	 * @return
	 * @return Map<String,Object>
	 * @throws @date
	 *             2016年6月12日 下午2:00:06
	 */
	private Map<String, Object> fillData(String loanapplyNo,O2oLoanUserEntity basic,CustomerBasicInfo customerBasicInfo) {
		Map<String, Object> data = new HashMap<>();
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		NumberFormat nf = new DecimalFormat(",###.00");
		if (loanapply == null) {
			return data;
		}
		LoanapplyExpand applyExpand = loanapplyExpandService.queryLoanapplyNo(loanapplyNo);
		O2oLoanUserEntity mate = loanUserService.findSpouseId(basic.getLoanId(), loanapplyNo);//配偶
		
//		O2oLoanUserEntity guarantor = loanUserService.queryDBById(loanapplyNo);//担保人
		CustomerAssetInfo asset = assetInfoService.queryById(loanapplyNo);
//		QueryCustomerVO vo = new QueryCustom = erVO();
//
//		vo.setCustomer_id(loanapply.getLoanId());
//
//		CustomerView customer = customerInfoService.geCustomerView(vo);
//		CustomerBasicInfoEntity basic = customer.getBasicInfo();
		if (mate != null && StringUtil.isNotBlank(mate.getSpouseId())) {// 配偶
//        	vo = new QueryCustomerVO();
//        	vo.setCustomer_id(basic.getMateId());
//        	CustomerBasicInfoEntity mate=customerInfoService.getCustomerBasicInfoEntity(vo);
			CustomerBasicInfo mateB = loanService.getCustomerEntityById(mate.getId());//配偶扩展信息
        	data.put("mateName", mate.getUserFullName());// 配偶
        	data.put("mateIdCard", mate.getDocumentNo());//配偶身份证
        	data.put("mateWorkUnit ", mateB.getWorkUnit());//配偶工作单位
         	data.put("mateMobile", mate.getUserPhone());//配偶手机号
//         	CustomerExpansionInfoEntity mateExp=customerInfoService.getCustomerExpansionInfoEntity(vo);
         
        }
		
		if (customerBasicInfo != null) {
			//============================begin========================================
			String recipientAdress="";// 有效联系地址/借款人的收件地址/居住地址
         	if (StringUtil.isNotBlank(customerBasicInfo.getRecipientProvince())) {
         		// 查数据字典--所在省，dd_no='9'
         		PubDditem p = pubDditemService.queryPubDditemCRM("9",customerBasicInfo.getRecipientProvince());// 所在省
				//PubDditem p = customerInfoService.getCustomerRecipientAddress(expan.getRecipientProvince(),"9");// 所在省
				if (p != null) {
					recipientAdress=recipientAdress+p.getItemName();
				}
			}
        
			if (StringUtil.isNotBlank(customerBasicInfo.getRecipientCity())) {
				// 查数据字典--所在市，dd_no='10'
				PubDditem p = pubDditemService.queryPubDditemCRM("10",customerBasicInfo.getRecipientCity());// 所在市
				//PubDditem p = customerInfoService.getCustomerRecipientAddress(expan.getRecipientCity(),"10");// 所在市
				if (p != null) {
					recipientAdress=recipientAdress+p.getItemName();
				}
			}
			
			if (StringUtil.isNotBlank(customerBasicInfo.getRecipientCounty())) {
				PubDditem p = pubDditemService.queryPubDditemCRM("11",customerBasicInfo.getRecipientCounty());// 所在县
				//PubDditem p = customerInfoService.getCustomerRecipientAddress(expan.getRecipientCounty(),"11");// 所在县
				if (p != null) {
					recipientAdress=recipientAdress+p.getItemName();
				}
			}

			if (customerBasicInfo.getRecipientAddress() != null) {
				recipientAdress = recipientAdress + customerBasicInfo.getRecipientAddress();
			}
			data.put("mateRecipientAdress", recipientAdress);// 有效联系地址/借款人的收件地址/居住地址
			data.put("address", recipientAdress);// 有效联系地址/借款人的收件地址/居住地址
			//============================end==========================================
			//============================begin========================================
			String accountAdress="";// 借款人身份证地址/户籍地址
			if (StringUtil.isNotBlank(customerBasicInfo.getAccountProvince())) {
				// 查数据字典--所在省，dd_no='9'
				PubDditem p = pubDditemService.queryPubDditemCRM("9",customerBasicInfo.getAccountProvince());// 所在省
				if (p != null) {
					accountAdress=accountAdress+p.getItemName();
				}
			}
			
			if (StringUtil.isNotBlank(customerBasicInfo.getAccountCity())) {
				// 查数据字典--所在市，dd_no='10'
				PubDditem p = pubDditemService.queryPubDditemCRM("10",customerBasicInfo.getAccountCity());// 所在市
				if (p != null) {
					accountAdress=accountAdress+p.getItemName();
				}
			}
			
			if (StringUtil.isNotBlank(customerBasicInfo.getAccountAounty())) {
				PubDditem p = pubDditemService.queryPubDditemCRM("11",customerBasicInfo.getAccountAounty());// 所在县
				if (p != null) {
					accountAdress=accountAdress+p.getItemName();
				}
			}
			
			if (customerBasicInfo.getPermanentresidence() != null) {
				accountAdress = accountAdress + customerBasicInfo.getPermanentresidence();
			}
			data.put("accountAdress", accountAdress);// 户籍地址
			//============================end=========================================
			if (String.valueOf(customerBasicInfo.getAge()) != null) {
				data.put("age", String.valueOf(customerBasicInfo.getAge()));// 借款人年龄
			} else {
				data.put("age", "");
			}
		}else {
			data.put("mateRecipientAdress", "");// 有效联系地址/借款人的收件地址/居住地址
			data.put("address", "");// 借款人身份证地址/户籍地址
			data.put("age", "");// 年龄
		}
		
//		CustomerExpansionInfoEntity exp = customer.getExpansionInfo();
//		CustomerAssetInfoEntity asset = customer.getAssetInfo();
		CustomerShopInfoEntity shop = new CustomerShopInfoEntity();
		List<CustomerShopInfoEntity> infoList = shopInfoService.list(loanapplyNo);//门店信息
		if (!infoList.isEmpty()) {
			if (infoList.size() > 1) {
				for (CustomerShopInfoEntity shopInfo : infoList) {
					if (shopInfo.getShoptype().equals("MAN")) {// 客户主门店里面的营业面积
						shop = shopInfo;
					}
				}
			} else {
				shop = infoList.get(0);
			}
		}

		if (basic != null) {
			data.put("lonerName", basic.getUserFullName());// 乙方(借款人)姓名
//			data.put("age", basic.getAge() == 0 ? "" : basic.getAge());// 借款人年龄
			String sex = "";
			if ("F".equals(basic.getSex())) {
				sex = "女";
			} else if ("M".equals(basic.getSex())) {
				sex = "男";
			}
			data.put("sex", sex);// 借款人性别
			data.put("idNumber", basic.getDocumentNo());// 身份证号码
			data.put("mobile", basic.getUserPhone());// 手机号
		}
		if (customerBasicInfo != null) {
			//============================begin========================================
			if (customerBasicInfo.getAccountProvince() != null) {
//				PubDditem p = customerInfoService.getCustomerRecipientAddress(exp.getAccountProvince(),"9");
				PubDditem p = pubDditemService.queryPubDditemCRM("9",customerBasicInfo.getAccountProvince());
				if (p != null) {
					data.put("accountProvince", p.getItemName());// 户口所在省
				}
			}

			if (customerBasicInfo.getAccountCity() != null) {
//				PubDditem p = customerInfoService.getCustomerRecipientAddress(exp.getAccountCity(),"10");
				PubDditem p = pubDditemService.queryPubDditemCRM("10",customerBasicInfo.getAccountCity());
				if (p != null) {
					data.put("accountCity", p.getItemName());// 户口所在市区
				}
			}
			if (customerBasicInfo.getEducation() != null) {
//				PubDditem p =customerInfoService.getCustomerRecipientAddress(exp.getEducation(),"18");
				PubDditem p = pubDditemService.queryPubDditemCRM("18",customerBasicInfo.getEducation());
				if (p != null) {
					data.put("education", p.getItemName());// 学历
				}
			}
			//============================end=========================================
		}

		if (asset != null) {
			data.put("ownEstateNum", asset.getOwnEstateNum());// 自有房产数量
			data.put("mortgageNum", asset.getMortgageNum());// 按揭房产数量
			data.put("notmortgageNum", asset.getOwnEstateNum() - asset.getMortgageNum());// 按揭房产数量
			data.put("ownVehiclesNum", asset.getOwnVehiclesNum());// 自有车辆数
			data.put("unsecuredNum", asset.getUnsecuredNum());// 无抵押车辆数
			data.put("vehicleMortgageNum", asset.getVehicleMortgageNum());// 辆数按揭数量

		}
		if (shop != null) {
			data.put("shopname", shop.getShopname());// 门店名称
			data.put("controllername", shop.getControllername());// 门店实际控制人
			
			if (!"".equals(shop.getControllerIdnum()) && shop.getControllerIdnum() != null) {
				data.put("controlleridnum", shop.getControllerIdnum());// 门店实际控制人身份证号码
			} else if (basic != null) {// 借款人
				data.put("controlleridnum", basic.getDocumentNo());// 身份证号码
			}
			if (!"".equals(shop.getControllerMobile()) && shop.getControllerMobile() != null) {
				data.put("controllermobile", shop.getControllerMobile());// 门店实际控制人电话
			} else if (basic != null) {// 借款人
				data.put("controllermobile", basic.getUserPhone());// 手机号
			}
			if (!"".equals(shop.getStupdate()) && shop.getStupdate() != null) {
				String datetime = DateUtils.formateStandDateString(shop.getStupdate());
				String year = datetime.substring(0, 4);
				String mouth = datetime.substring(5, 7);
				data.put("year", year);// 门店成立年
				data.put("mouth", mouth);// 门店成立月
			}
			if (shop.getIscontroller() != null && shop.getIscontroller().equals("SAM1")) {
				data.put("shopIdNumber", basic.getDocumentNo());// 门店电话?
			}
			data.put("shopTelephone", shop.getTelephone());// 门店电话
			data.put("shopaddress", shop.getShopaddress());// 门店地址
			data.put("businessarea", shop.getBusinessarea());// 营业面积
			data.put("businesshours", shop.getBusinesshours());// 营业时间
			data.put("mainproducts", shop.getMainproducts());// 主要经营产品
			data.put("officeaddress", shop.getOfficeaddress());// 丙方单位地址
			data.put("organization_form", shop.getOrganizationForm());// 组织形式
			data.put("blr_number", shop.getBlrNumber());// 营业执照注册号
			data.put("registered ", shop.getRegistered());//注册地
		}

		if (loanapply != null) {
			if (loanapply.getLtd() != null) {
				ActOrgEntity actOrgEntity = sysOrgService.getOrgByUnitNo(loanapply.getLtd());
				data.put("ltd_mobile", actOrgEntity.getSponsorTel());// 经营单位电话
				data.put("ltd_office_address", actOrgEntity.getOfficeAddress());// 经营单位办公地址
				data.put("ltd_name", actOrgEntity.getOrgFullName());// 经营名称
			}
			data.put("receiveBank", loanapply.getReceiveBank());// 借款银行名称
			data.put("open_account_bank_full_name", loanapply.getReceiveBank());// 借款银行名称
			data.put("guarantee_way_xinyong", "信用");// 担保方式
			data.put("bankActno", loanapply.getBankActno());// 贷款账号
/*			
			// 送审银行
			if ("SPDBGZ".equals(loanapply.getBankLoanName())) {// 浦发广州分行
				data.put("billCode1", "浦发银行-合-" + loanapply.getBillCode());// 协议编号
			} else if ("JCB".equals(loanapply.getBankLoanName())) {
				data.put("billCode1", "江西银行-合-" + loanapply.getBillCode());// 协议编号
			} else if ("GACZ".equals(loanapply.getBankLoanName())) {
				data.put("billCode1", "村镇银行-合-" + loanapply.getBillCode());// 协议编号
			} else if ("QLB".equals(loanapply.getBankLoanName())) {
				data.put("billCode1", "齐鲁银行-合-" + loanapply.getBillCode());// 协议编号
			} else if ("ZLB".equals(loanapply.getBankLoanName())) {
				data.put("billCode1", "中旅银行-合-" + loanapply.getBillCode());// 协议编号
			} else if ("BC".equals(loanapply.getBankLoanName())) {
				data.put("billCode1", "中国银行-合-" + loanapply.getBillCode());// 协议编号
			} else if ("ZZB".equals(loanapply.getBankLoanName())) {
				data.put("billCode1", "郑州银行-合-" + loanapply.getBillCode());// 协议编号
			} else if ("EA".equals(loanapply.getBankLoanName())) {
				data.put("billCode1", "怡亚通-合-" + loanapply.getBillCode());// 协议编号
			} else {
				data.put("billCode1", "国安-合-" + loanapply.getBillCode());// 协议编号
			}
*/
	
			/**
			 * 送审银行
			 * @author LMX
			 * @date 2017年9月26日 下午4:20:50
			 */
			String bankLoanName = o2oPubDdItemService.findPubdditemNameByCode("BANKTYPEO2O",
					loanapply.getBankLoanName());// 送审银行
			if (!"".equals(bankLoanName) && bankLoanName != null) {
				if ("SPDBGZ".equals(loanapply.getBankLoanName())) {// 浦发广州分行
					bankLoanName = "浦发银行";
				} else if ("GACZ".equals(loanapply.getBankLoanName())) {// 国安村镇银行
					bankLoanName = "村镇银行";
				}
				data.put("billCode1", bankLoanName + "-合-" + loanapply.getBillCode());// 协议编号
			}
			
			data.put("billCode", "国安-借-" + loanapply.getBillCode());// 贷款编号
//			data.put("billCode1", "国安-合-" + loanapply.getBillCode());// 协议编号
			data.put("billCode2",  "中行-借-"+loanapply.getBillCode());// 贷款编号
			if (!"".equals(loanapply.getEaMount()) && loanapply.getEaMount() != null) {
				String bankAmountBigWrite = MoneyUtil
						.toChinese(formatComma2BigDecimal(loanapply.getEaMount()).toString());
				System.out.println(bankAmountBigWrite);

				data.put("bankAmountBigWrite", bankAmountBigWrite);// 银行批复金额大写

				data.put("loanAmount", "￥" + formatComma2BigDecimal(loanapply.getEaMount()));// 申请金额万元

				data.put("bankAmount", nf.format(formatComma2BigDecimal(loanapply.getEaMount())));// 银行批复金额小写

				String[] mountItem = buildMountNumber(loanapply.getEaMount());
				for (int i = 0; i < mountItem.length; i++) {
					data.put("mountItem" + i, mountItem[i]);
				}
			}

			if (loanapply.getLoanrate() != null) {
				BigDecimal loanrate = loanapply.getLoanrate().multiply(new BigDecimal(100));
				data.put("loanrate", formatComma2BigDecimal(loanrate));// 借款利率
			}
			data.put("loanTerm", loanapply.getLoanTerm());// 借款期限
			if (loanapply.getRepayMentway() != null) {
				if (loanapply.getRepayMentway().equals("AKT")) {
					data.put("repayMentway", "等额本金");// 还款方式
					data.put("repayMentwayNo", "(2)");
				} else if (loanapply.getRepayMentway().equals("RMT")) {
					data.put("repayMentway", "按月付息，到期还本");// 还款方式
					data.put("repayMentwayNo", "(1)");
				} else {
					data.put("repayMentway", "等额本息");// 还款方式
					data.put("repayMentwayNo", "(2)");
				}
			}

			data.put("bank_account", loanapply.getBankAccount());// 银行卡号(放款和还款卡号)

			if (loanapply.getGuarAnteeWay() != null) {

				com.eascs.admin.o2o.internal.entity.PubDditem p = pubDditemService.queryPubDditem("9941", loanapply.getGuarAnteeWay());
				if (p != null) {
					data.put("guar_antee_way", p.getItemName());// 担保方式
				}
			}

			if (loanapply.getManagefeerate() != null) {
				BigDecimal managefeerate = loanapply.getManagefeerate().multiply(new BigDecimal(100));
				data.put("managefeerate", formatComma2BigDecimal(managefeerate));// 管理费率
			}
			if (loanapply.getDepositrate() != null) {
				BigDecimal depositrate = loanapply.getDepositrate().multiply(new BigDecimal(100));
				data.put("depositrate", formatComma2BigDecimal(depositrate));// 保证金费率
			}

			if (loanapply.getRisk() != null) {
				NumberFormat nfd = new DecimalFormat("#0.0000");// 小数点保留四位，零不省略
				BigDecimal saferate = loanapply.getRisk().multiply(new BigDecimal(100));// 乘以100
//				data.put("saferate", formatComma2BigDecimal(saferate));// 风险补偿金费率
				data.put("saferate", nfd.format(saferate));// 风险补偿金费率
			}
			if (loanapply.getPaymentType() != null) {
				com.eascs.admin.o2o.internal.entity.PubDditem p = pubDditemService.queryPubDditemO2o("4", loanapply.getPaymentType());
				if (p != null) {
					data.put("paymentType", p.getItemName());// 借款用途
				}

			}
		}
		if (applyExpand != null) {
			if (applyExpand.getRecManger() != null) {
				System.out.println("管理费:" + formatComma2BigDecimal(applyExpand.getRecManger()));
				data.put("rec_manger", "￥" + formatComma2BigDecimal(applyExpand.getRecManger()));// 管理费
			}
			if (applyExpand.getRecDeposite() != null) {
				data.put("rec_deposite", "￥" + formatComma2BigDecimal(applyExpand.getRecDeposite()));// 保证费
			}
			if (applyExpand.getRecRisk() != null) {
				data.put("rec_risk", "￥" + formatComma2BigDecimal(applyExpand.getRecRisk()));// 保证费
			}
			BigDecimal total = new BigDecimal("0");
			BigDecimal recManger = new BigDecimal("0");
			BigDecimal recDeposite = new BigDecimal("0");
			BigDecimal recRisk = new BigDecimal("0");
			recManger = applyExpand.getRecManger() == null ? recManger : applyExpand.getRecManger();
			recDeposite = applyExpand.getRecDeposite() == null ? recDeposite : applyExpand.getRecDeposite();
			recRisk = applyExpand.getRecRisk() == null ? recRisk : applyExpand.getRecRisk();
			total = recManger.add(recDeposite).add(recRisk);
			data.put("rec_total_samll", formatComma2BigDecimal(total));// 保证费
			data.put("rec_total_big", MoneyUtil.toChinese(formatComma2BigDecimal(total).toString()));// 保证费

		}

		return data;

	}
	
	
	/**
	 * @Title: downloadMateDbPdf
	 * @Description: 配偶担保打印
	 * @author 张庆奇
	 * @param httpServletResponse
	 * @param request
	 * @param loanapplyNo
	 * @return void
	 * @throws
	 * @date 2017年4月17日 下午1:54:47
	 */
	@RequestMapping(value = "/downloadMateDbPdf", method = RequestMethod.GET)
	public void downloadMateDbPdf(HttpServletResponse httpServletResponse, HttpServletRequest request,
			String loanapplyNo) {
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		if(loanapply==null){
			return;
		}
//		QueryCustomerVO vo = new QueryCustomerVO();
//		vo.setCustomer_id(loanapply.getLoanId());
//		CustomerBasicInfoEntity customer = customerInfoService.getCustomerBasicInfoEntity(vo);
//		if(customer==null){
//			return;
//		}
		
		O2oLoanUserEntity loanUserEntity = loanService.findLoanUserEntity(loanapplyNo, loanapply.getLoanId());
		CustomerBasicInfo customerBasicInfo = loanService.getCustomerEntityById(loanUserEntity.getId());
	
		//最后需要生产的模板文件
		String[] classPathFiles={ "/pdfTemplate/mateDb.pdf"};
		
			Map<String, Object> data = fillData(loanapplyNo,loanUserEntity,customerBasicInfo);

			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			try {
				PdfBuilder.mergePdfFilesAndBuild(classPathFiles, data, outputStream);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
			OutputStream os = null;
			try {
				String outfile = "";
				outfile = loanUserEntity.getCustomerName() + "-配偶担保人打印.pdf";
				if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
					outfile = URLEncoder.encode(outfile, "UTF-8");
				} else {
					outfile = new String(outfile.getBytes("UTF-8"), "ISO8859-1");
				}
				os = httpServletResponse.getOutputStream();
				httpServletResponse.reset();
				httpServletResponse.setContentType("application/pdf");
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
				os.write(outputStream.toByteArray());
				os.flush();
			} catch (IOException e) {
				throw new RuntimeIOException(e);
			} finally {
				IoUtil.close(os);
			}
		
	}
	
	
	/**
	 * @Title: downloadBusinessDbPdf
	 * @Description: 企业担保打印
	 * @author 张庆奇
	 * @param httpServletResponse
	 * @param request
	 * @param loanapplyNo
	 * @return void
	 * @throws
	 * @date 2017年4月17日 下午1:54:47
	 */
	@RequestMapping(value = "/downloadBusinessDbPdf", method = RequestMethod.GET)
	public void downloadBusinessDbPdf(HttpServletResponse httpServletResponse, HttpServletRequest request,
			String loanapplyNo) {
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		if(loanapply==null){
			return;
		}
//		QueryCustomerVO vo = new QueryCustomerVO();
//		vo.setCustomer_id(loanapply.getLoanId());
//		CustomerBasicInfoEntity customer = customerInfoService.getCustomerBasicInfoEntity(vo);
//		if(customer==null){
//			return;
//		}
		
		O2oLoanUserEntity loanUserEntity = loanService.findLoanUserEntity(loanapplyNo, loanapply.getLoanId());
		CustomerBasicInfo customerBasicInfo = loanService.getCustomerEntityById(loanUserEntity.getId());
	
		//最后需要生产的模板文件
		String[] classPathFiles={ "/pdfTemplate/businessDb.pdf"};
		
			Map<String, Object> data = fillData(loanapplyNo,loanUserEntity,customerBasicInfo);

			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			try {
				PdfBuilder.mergePdfFilesAndBuild(classPathFiles, data, outputStream);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
			OutputStream os = null;
			try {
				String outfile = "";
				outfile = loanUserEntity.getCustomerName() + "-企业担保打印.pdf";
				if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
					outfile = URLEncoder.encode(outfile, "UTF-8");
				} else {
					outfile = new String(outfile.getBytes("UTF-8"), "ISO8859-1");
				}
				os = httpServletResponse.getOutputStream();
				httpServletResponse.reset();
				httpServletResponse.setContentType("application/pdf");
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
				os.write(outputStream.toByteArray());
				os.flush();
			} catch (IOException e) {
				throw new RuntimeIOException(e);
			} finally {
				IoUtil.close(os);
			}
		
	}
	

	/**
	 * @Title: downloadDbrPdf
	 * @Description:担保人打印
	 * @author 张庆奇
	 * @param httpServletResponse
	 * @param request
	 * @param loanapplyNo
	 * @return void
	 * @throws
	 * @date 2017年4月20日 下午1:18:49
	 */
	@RequestMapping(value = "/downloadDbrPdf", method = RequestMethod.GET)
	public void downloadDbrPdf(HttpServletResponse httpServletResponse, HttpServletRequest request,
			String customer_id,String loanapplyNo) {
		O2oLoanapplyEntity loanapply = loanService.findById(loanapplyNo);
		if(loanapply==null){
			return;
		}
//		QueryCustomerVO vo = new QueryCustomerVO();
//		vo.setCustomer_id(loanapply.getLoanId());
//		CustomerBasicInfoEntity customer = customerInfoService.getCustomerBasicInfoEntity(vo);
//		if(customer==null){
//			return;
//		}
//		vo.setCustomer_id(customer_id);
//		CustomerBasicInfoEntity dbr = customerInfoService.getCustomerBasicInfoEntity(vo);
//		vo.setShoptype("MAN");
//		CustomerShopInfoEntity dbrShop=customerInfoService.getCustomerShopInfoEntity(vo);
		
		O2oLoanUserEntity loanUserEntity = loanService.findLoanUserEntity(loanapplyNo, loanapply.getLoanId());//
		CustomerBasicInfo customerBasicInfo = loanService.getCustomerEntityById(loanUserEntity.getId());
		O2oLoanUserEntity dbr = loanUserService.queryDBById(loanapplyNo);//担保人
		CustomerBasicInfo dbrB = loanService.getCustomerEntityById(dbr.getId());//担保人扩展信息
		
		CustomerShopInfoEntity dbrShop = new CustomerShopInfoEntity();
		List<CustomerShopInfoEntity> infoList = shopInfoService.list(loanapplyNo);//门店信息
		if (!infoList.isEmpty()) {
			if (infoList.size() > 1) {
				for (CustomerShopInfoEntity shopInfo : infoList) {
					if (shopInfo.getShoptype().equals("MAN")) {// 客户主门店里面的营业面积
						dbrShop = shopInfo;
					}
				}
			} else {
				dbrShop = infoList.get(0);
			}
		}
		//最后需要生产的模板文件
		String[] classPathFiles={ "/pdfTemplate/dbr.pdf"};
		
			Map<String, Object> data = fillData(loanapplyNo,loanUserEntity,customerBasicInfo);
			data.put("dbrName", dbr.getCustomerName());//担保人
			data.put("dbrIdcard", dbr.getDocumentNo());//担保人身份证
			data.put("dbrWorkUnit", dbrB.getWorkUnit());//担保人工作单位
			data.put("dbrMobile", dbr.getUserPhone());//担保人手机号
			data.put("dbrRegistered", dbrShop.getRegistered());//担保人注册地
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			try {
				PdfBuilder.mergePdfFilesAndBuild(classPathFiles, data, outputStream);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
			OutputStream os = null;
			try {
				String outfile = "";
				outfile = loanUserEntity.getCustomerName() + "-担保人打印.pdf";
				if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
					outfile = URLEncoder.encode(outfile, "UTF-8");
				} else {
					outfile = new String(outfile.getBytes("UTF-8"), "ISO8859-1");
				}
				os = httpServletResponse.getOutputStream();
				httpServletResponse.reset();
				httpServletResponse.setContentType("application/pdf");
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
				os.write(outputStream.toByteArray());
				os.flush();
			} catch (IOException e) {
				throw new RuntimeIOException(e);
			} finally {
				IoUtil.close(os);
			}
		
	}
	


	private boolean isDouble(String value) {
		try {
			Double.parseDouble(value);
			if (value.contains("."))
				return true;
			return false;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	private boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	private boolean isNumber(String value) {
		return isInteger(value) || isDouble(value);
	}

	private BigDecimal formatComma2BigDecimal(Object obj) {
		String val = String.valueOf(obj);
		if (val == null)
			return new BigDecimal("0.00");

		val = val.replaceAll(",", "");
		if (!isNumber(val))
			return new BigDecimal("0.00");

		BigDecimal decimal = new BigDecimal(val);
		decimal = decimal.setScale(2, BigDecimal.ROUND_UP);

		return decimal;

	}

	private static String[] buildMountNumber(Number number) {
		DecimalFormat df = new DecimalFormat("0.00");
		String mountStr = df.format(number);
		mountStr = "￥" + mountStr.replace(".", "");
		String[] numberArray = new String[10];
		int j = 0;
		for (int i = 0; i < numberArray.length; i++) {
			numberArray[i] = "";
			if (mountStr.length() >= 10 - i) {
				numberArray[i] = mountStr.substring(j, j + 1);
				j++;
			}
		}
		return numberArray;
	}
}
